########################################################################
# PLS 206 — Week 9 live coding: trees, random forests, neural networks
# Grey Monroe, Fall 2026
########################################################################

# install.packages(c("rpart", "rpart.plot", "randomForest", "neuralnet", "ggplot2"))
library(rpart)
library(rpart.plot)
library(randomForest)
library(neuralnet)
library(ggplot2)

########################################################################
# Helpers (run this block once)
########################################################################

# R² of predictions on new data (1 = perfect, 0 = no better than the mean)
r2 <- function(obs, pred) 1 - sum((obs - pred)^2) / sum((obs - mean(obs))^2)

# partial dependence, one curve per group: set every row to each value of `var`, average the predictions
partial <- function(model, data, var, values, by) {
  grid <- expand.grid(x = values, by = levels(data[[by]]))
  grid$yhat <- sapply(seq_len(nrow(grid)), function(i) {
    d <- data; d[[var]] <- grid$x[i]; d[[by]] <- factor(grid$by[i], levels = levels(data[[by]]))
    mean(predict(model, d))
  })
  grid
}

# neuralnet needs numbers on similar scales: factors -> 0/1 columns, scaled with the TRAINING means and SDs
nn_inputs <- function(formula, train, new = train) {
  X  <- model.matrix(formula, train)[, -1]
  Xn <- model.matrix(formula, new)[, -1]
  colnames(X) <- colnames(Xn) <- make.names(colnames(X))
  as.data.frame(scale(Xn, colMeans(X), apply(X, 2, sd)))
}

########################################################################
# 1. One tree: 300 cattle
########################################################################

cattle   <- read.csv("https://greymonroe.github.io/PLS_206/data/cattle_health.csv", stringsAsFactors = TRUE)
new_herd <- read.csv("https://greymonroe.github.io/PLS_206/data/cattle_health_new.csv", stringsAsFactors = TRUE)
cattle$status   <- factor(ifelse(cattle$healthy == 1, "healthy", "sick"), levels = c("sick", "healthy"))
new_herd$status <- factor(ifelse(new_herd$healthy == 1, "healthy", "sick"), levels = c("sick", "healthy"))

ggplot(cattle, aes(grass, healthy, colour = breed)) + geom_jitter(height = 0.04, width = 0) +
  facet_wrap(~breed) + theme_classic()

tree <- rpart(status ~ grass + breed, data = cattle)
rpart.plot(tree)

pred_tree <- predict(tree, new_herd, type = "class")      # predicted class for each new cow
mean(pred_tree == new_herd$status)                        # accuracy on the new herd

########################################################################
# 2. A random forest
########################################################################

set.seed(1)
rf <- randomForest(status ~ grass + breed, data = cattle, ntree = 500)
rf                      # OOB error: cows each tree never saw
plot(rf)                # OOB error vs number of trees

mean(predict(rf, new_herd) == new_herd$status)            # accuracy on the new herd

set.seed(1)
bag <- randomForest(status ~ grass + breed, data = cattle, mtry = 2)   # mtry = all predictors: bagging
bag

# classical models can bend too: logistic regression, straight and curved
glm1 <- glm(healthy ~ grass + breed, family = binomial, data = cattle)
glm2 <- glm(healthy ~ breed * poly(grass, 2), family = binomial, data = cattle)
mean((predict(glm1, new_herd, type = "response") > 0.5) == new_herd$healthy)   # straight: 54%
mean((predict(glm2, new_herd, type = "response") > 0.5) == new_herd$healthy)   # curved: 76%

########################################################################
# 3. A harder problem: 800 wheat fields, 10 predictors
########################################################################

fields     <- read.csv("https://greymonroe.github.io/PLS_206/data/wheat_fields.csv", stringsAsFactors = TRUE)
new_fields <- read.csv("https://greymonroe.github.io/PLS_206/data/wheat_fields_new.csv", stringsAsFactors = TRUE)

m_lm <- lm(yield ~ ., data = fields)
r2(new_fields$yield, predict(m_lm, new_fields))           # 0.38

set.seed(1)
rf_fields <- randomForest(yield ~ ., data = fields, ntree = 500, importance = TRUE)
rf_fields                                                 # mtry = 3; % Var explained = OOB R²
plot(rf_fields)
r2(new_fields$yield, predict(rf_fields, new_fields))      # 0.77

# importance: the shuffle test (type = 1) is the one to use for inference
varImpPlot(rf_fields, type = 1)
importance(rf_fields)                 # both columns: %IncMSE (shuffle) and IncNodePurity (split credit)

# partial dependence: the shape of one effect
partialPlot(rf_fields, fields, frost_days)
partialPlot(rf_fields, fields, soil_pH)

# one curve per group: interactions
pd_heat <- partial(rf_fields, fields, "heat_days", 0:35, by = "variety")
ggplot(pd_heat, aes(x, yhat, colour = by)) + geom_line(linewidth = 1.2) + theme_classic()

########################################################################
# 4. A neural network
########################################################################

cattle_nn <- nn_inputs(~ grass + breed, cattle)           # grass scaled, Hereford as 0/1
cattle_nn$healthy <- cattle$healthy
head(cattle_nn)

set.seed(1)
nn <- neuralnet(healthy ~ grass + breedHereford, data = cattle_nn, hidden = 3, rep = 5,
                linear.output = FALSE, err.fct = "ce", stepmax = 1e5)
nn$result.matrix["error", ]                               # one error per random start
best <- which.min(nn$result.matrix["error", ])
plot(nn, rep = best)

new_nn <- nn_inputs(~ grass + breed, cattle, new_herd)    # new cows, scaled with the TRAINING means and SDs
p_nn <- predict(nn, new_nn, rep = best)[, 1]              # P(healthy)
mean((p_nn > 0.5) == new_herd$healthy)                    # accuracy on the new herd
